package com.dongdongqiang.common.query.mysql;


import com.dongdongqiang.common.query.QueryException;
import org.apache.commons.lang3.StringUtils;

/**
 * 查询sql转变为统计记录数的sql
 * Created by zhangzhenbin on 2016/12/13.
 */
public class MysqlQuerySqlToCountSqlConvert {
    final static String SELECT = "select ";
    final static String FROM = " from ";
    final static String COUNT_1_ = " count(1) ";
    public static String getCountSql(String querySql) throws QueryException {
        if (querySql == null || querySql.length() == 0)
            throw new QueryException("查询sql为空，请检查查询sql传入值");
        //去除前方空格
        querySql = StringUtils.removeStart(querySql.toLowerCase()," ");
        StringBuilder querySqlBuilder = new StringBuilder(querySql);
        //判断是否是select语句
        if (querySqlBuilder.indexOf(SELECT) != 0)
            throw new QueryException("查询sql异常，请检查查询sql传入值");
        int indexOfFrom = querySqlBuilder.indexOf(FROM);
        if (indexOfFrom == -1)
            throw new QueryException("查询sql异常，请检查查询sql传入值");
        return querySqlBuilder.delete(SELECT.length(), indexOfFrom).insert(SELECT.length(), COUNT_1_).toString();
    }

    public static void main(String[] args) {
        try {
            String testSql = "select sys_param.*,sys_param.id from sys_param where 1 = 1 and activate = 1";
            System.out.println("-----------------before-----------------");
            System.out.println(testSql);
            System.out.println("-----------------after-----------------");
            System.out.println(getCountSql(testSql));
        } catch (QueryException e) {
            e.printStackTrace();
        }
    }
}
